import React from 'react';
import {
    View,
    Text,
    FlatList,
    TouchableOpacity,
    Dimensions,
    Image,
} from 'react-native';
import {
    Modal,
} from '@ant-design/react-native';

import NavigationBar from '../../common/NavigationBar';
import {BASE_URL} from '../../common/BASE_URL';
import HttpUtils from '../../expand/dao/HttpUtils';
import {Constant, StylesConstant} from '../../common/Constant';
import StorageUtil from '../../utils/StorageUtil';
import NavigationUtil from '../../navigators/NavigationUtil';
import Utils from '../../utils/Utils';
import GlobalStyles from '../../common/styles/GlobalStyles';
import {Tabs} from '@ant-design/react-native';
import ChooseReportType from './components/ChooseReportType'
import AddPersonalInfoForm from './components/AddPersonalInfoForm'
import PersonalInfoForm from "./components/PersonalInfoForm";
import CaseInfoForm from "./components/CaseInfoForm";
import ToastUtil from '../../utils/ToastUtil';
import styles from './styles'
import CaseDocument from "./components/CaseDocument";
import DealWay from "./components/DealWay";
import AddEnterpriseInfoForm from "./components/AddEnterpriseInfoForm";
import ProviderInfoForm from "./components/ProviderInfoForm";

const saveCaseReportUrl =  BASE_URL.apiBaseUrl + '/api/caseInfo'
const saveAcceptCaseUrl =  BASE_URL.apiBaseUrl + '/api/acceptCases'
const saveCaseRecordsUrl =  BASE_URL.apiBaseUrl + '/api/inspectionRecords'

// 查询巡查待办详情
const queryInspectionByCode = BASE_URL.apiBaseUrl + '/app/inspectionRecords/findViewByCaseCode'
const queryCaseByCode = BASE_URL.apiBaseUrl + '/app/viewCaseInfo/findByCaseCode'
const queryAcceptByCode = BASE_URL.apiBaseUrl + '/app/viewAcceptCases/findByCaseCode'

export default class CaseReport extends React.Component {
    constructor(props) {
        super(props);
        // 获取参数
        let tabIndex = 0;
        this.state = {
            submitType: 'post',// post 新增 put 修改
            WayId:null,//巡查方式id
            reportType: '',
            tabIndex: tabIndex,
            isLoading: true, // list加载状态
            // 个人信息
            caseLitigants: [],
            providerObj: [],
            // 案件信息
            caseInfo: {},
            // 文书表单
            documentInfo: {},
            // 文书
            caseTextData: [],
            //填写的个人信息列表
            userInfoList:[],
            avoidCaseList:[],//获取上级文书列表
            caseCode:null,
        };
      
    }

       // 获取个人和企业填报信息列表
    getDetailInfo=(info)=>{
        this.setState({
            userInfoList:info
        })
    }

    componentDidMount() {
        // this.loadData();
        const {type, caseCode, matterId, linkId, submitType} = this.props.navigation.state.params;
        if(submitType){
            this.setState({
                submitType:submitType
            })
        }
        // 全局缓存
        this.type = type
        this.matterId = matterId
        this.linkId = linkId;
        this.caseCode = caseCode
        if(type && caseCode){
            let queryUrl = queryCaseByCode;
            if(type === 'caseInfo'){
                queryUrl = queryCaseByCode;
            }else if(type === 'inspection'){
                queryUrl = queryInspectionByCode;
            }else if(type === 'clue'){
                queryUrl = queryAcceptByCode;
            }
            const key = ToastUtil.loading('加载中')
            HttpUtils.request({
                url: queryUrl,
                params: {
                    caseCode
                }
            }).then(res=>{
                ToastUtil.remove(key)
                if(res && !res.status){
                    let reportTypeStr = "";
                    let providerObj = {};
                    if(type === 'clue'){
                        reportTypeStr = "clue";
                        providerObj = {
                            provider: res.provider,
                            providerTel: res.providerTel,
                            providerAddress : res.providerAddress,
                            providerEmail: res.providerEmail,
                            providerGender: res.providerGender,
                            providerGenderLabel: res.providerGender===0?'女':'男',
                            providerUnitName:res.unit?res.unit.name:'',
                        }
                    }else if(res.counterpartType === 0){
                        reportTypeStr = "personal";
                    }else if(res.counterpartType === 1){
                        reportTypeStr = "enterprise";
                    }else {
                        reportTypeStr = "personal";
                    }
                    // console.log("resList",res)
                    this.setState({
                        reportType: reportTypeStr,
                        caseLitigants: res.caseLitigants,
                        providerObj:providerObj,
                        caseInfo:{
                            ...res,
                            undertakerName: res.undertakerOfficer?res.undertakerOfficer.name: '',
                            undertaker2Name: res.undertakerOfficer2?res.undertakerOfficer2.name: '',
                            undertakerDept: deptId,
                            undertakerDeptLabel : deptName,
                            caseTimeStr: res.caseTime? new Date(res.caseTime).Format('yyyy-MM-dd hh:mm:ss'): '',
                            inspectionEndTimeStr: res.inspectionEndTime? new Date(res.inspectionEndTime).Format('yyyy-MM-dd hh:mm:ss'): '',
                            industriesLabel:res.industries.name,
                            industriesCode:res.industries.code,
                        },
                        avoidCaseList: res.caseTexts,
                        caseCode:caseCode
                    })
                    const {dept} = res
                    let deptId = '', deptName = ''
                    if(dept){
                        deptId = dept.id
                        deptName = dept.name
                    }

                    this.refs.providerObj && this.refs.providerObj.setData(providerObj)
                    this.refs.caseLitigants && this.refs.caseLitigants.setData(res.caseLitigants)
                    this.refs.caseInfoForm && this.refs.caseInfoForm.setCaseInfo({
                        ...res,
                        undertakerName: res.undertakerOfficer?res.undertakerOfficer.name: '',
                        undertaker2Name: res.undertakerOfficer2?res.undertakerOfficer2.name: '',
                        undertakerDept: deptId,
                        undertakerDeptLabel : deptName,
                        caseTimeStr: res.caseTime? new Date(res.caseTime).Format('yyyy-MM-dd hh:mm:ss'): '',
                        inspectionEndTimeStr: res.inspectionEndTime? new Date(res.inspectionEndTime).Format('yyyy-MM-dd hh:mm:ss'): '',
                        industriesLabel:res.industries.name,
                        industriesCode:res.industries.code,
                    })
                }
            }).catch(()=>{
                ToastUtil.remove(key)
            })
        }

    }

   

    loadData() {
        const {tabIndex} = this.state;
        this.setState({
            isLoading: false,
        })
    }
    _handleChooseReportType(type){
        this.setState({
            reportType: type
        })
    }
    render() {
        const {navigation} = this.props;
        const {tabIndex,reportType,submitType} = this.state;
        return (
            <View style={GlobalStyles.pageContainer}>
                {/* 自定义顶部导航条 */}
                <NavigationBar
                    navigation={navigation}
                    headerBackTitle={'案事件详情'}
                />
                <View style={{flex: 1}}>
                    {submitType === 'post'?(
                        reportType?this._renderTabs():
                            <ChooseReportType chooseType={(item)=>this._handleChooseReportType(item)}/>
                        )
                        :this._renderTabs()
                    }
                </View>
            </View>
        );
    }
    formDataChange(key,value){
        this.setState({
            [key]: value
        })
    }

    _renderTabs(){
        const {tabIndex,reportType} = this.state;
        const reportTypeStr = reportType==='personal'?'个人':reportType==='enterprise'?'单位':reportType==='clue'?'提供人':'个人'
        return (
            <>
                <Tabs
                    style={[styles.container, GlobalStyles.bgGrey]}
                    initialPage={tabIndex}
                    tabBarTextStyle={GlobalStyles.tabsTextStyle}
                    tabBarUnderlineStyle={GlobalStyles.tabsLineStyle}
                    tabBarActiveTextColor={GlobalStyles.tabBarActiveTextColor}
                    tabBarInactiveTextColor={GlobalStyles.tabBarInactiveTextColor}
                    onChange={(tab, index) => this.handleTabChange(tab, index)}
                    tabs={[
                        {title: reportTypeStr},
                        {title: '案件信息'},
                        // {title: '证据材料'},
                        // {title: '视频存证'},
                        {title: '处理方式'},
                        {title: '案件文书'},
                    ]}>
                    {reportType === 'personal'?
                    <View tabLabel="个人" style={{flex: 1,fontSize:14}}>
                        <AddPersonalInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}
                                             transmitList={this.getDetailInfo}
                                             />
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View> 
                    : reportType === 'enterprise'?
                    <View tabLabel="单位" style={{flex: 1,fontSize:14}}>
                        <AddEnterpriseInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View> 
                    : reportType === 'clue'?
                    <View tabLabel="提供人" style={{flex: 1,fontSize:14}}>
                        <ProviderInfoForm ref={'providerObj'} providerObj={this.state.providerObj}
                                             onChange={(data)=>this.formDataChange('providerObj',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View> 
                    :
                    <View tabLabel="个人" style={{flex: 1,fontSize:14}}>
                        <AddPersonalInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View>
                    }
                    <View tabLabel="案件信息" style={{flex: 1,fontSize:14}}>
                        <CaseInfoForm type={this.type} ref={'caseInfoForm'} 
                                    caseInfo={this.state.caseInfo}
                                    personInfo={this.state.userInfoList}
                                    onChange={(data)=>this.formDataChange('caseInfo', data)}/>
                    </View>
                    {/*<View tabLabel="证据材料" style={{flex: 1}}><Text>1</Text></View>*/}
                    {/*<View tabLabel="视频存证" style={{flex: 1}}><Text>1</Text></View>*/}
                    <View tabLabel="处理方式" style={{flex: 1,fontSize:14}}>
                        <DealWay type={this.type} linkId={this.linkId} caseCode={this.caseCode}
                                 submitType={this.state.submitType} reportType={this.state.reportType}
                                 hadCaseDeal={(id)=>this._hadCaseDealWay(id)}
                                 onChange={(data)=>this.formDataChange('documentInfo',data)}/>
                    </View>
                    <View tabLabel="案件文书" style={{flex: 1,fontSize:14}}>
                        <CaseDocument
                            documentInfo={this.state.documentInfo}
                            caseTextData={this.state.caseTextData}
                            avoidCaseList={this.state.avoidCaseList}
                            caseInfo={this.state.caseInfo}
                            caseCode={this.state.caseCode}
                            caseLitigants={this.state.caseLitigants}
                            onChanges={(data)=>{this.handleCase(data)}}
                            onChange={(data)=>this.formDataChange('caseTextData',data)}
                        />
                    </View>
                </Tabs>
                {this.state.submitType!=='detail'?this._renderBottomBtns():<View><Text></Text></View>}
            </>
        )
    }

    _renderBottomBtns(){
        const {type} = this.props
        return (
            <View style={styles.bottomBtnsPanel}>
                <TouchableOpacity
                    style={styles.saveBtn}
                    onPress={()=>this._temporaryStorage()}
                >
                    <Text style={styles.saveBtnText}>暂存</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.submitBtn}
                    onPress={()=>this._handleSave()}
                >
                    <Text style={styles.submitBtnText}>提交</Text>
                </TouchableOpacity>
            </View>
        )
    }
    _temporaryStorage(){
    
    }
    _hadCaseDealWay(id){
        this.setState({
            WayId:id
        })
    }

    handleCase(data){
        this.setState({
            avoidCaseList:data
        })
    }

    _handleSave(){
        let {submitType,reportType,caseInfo,caseLitigants,providerObj,documentInfo,caseTextData} = this.state
        caseTextData=[...caseTextData,...this.state.avoidCaseList]
        let counterpartType = 0;
        if(reportType === 'enterprise'){
            counterpartType = 1;
        }
        if(caseInfo){
            // {
            //   text: 'Cancel',
            //   onPress: () => console.log('cancel'),
            //   style: 'cancel',
            // },
           let mustArr=[ //详情必填验证
            //    'caseTitle',
               'undertakerName',
               'undertaker2Name',
               'caseTimeStr',
               'inspectionEndTimeStr',
               'sourceTypeLable',
               'caseBrief',
           ]
          if(caseInfo){
//            mustArr
            console.log("UP caseInfo",caseInfo)
            let type=false
            for(let i=0,item=mustArr;i<mustArr.length;i++){
                if(!caseInfo[item[i]]||caseInfo[item[i]]==''||caseInfo[item[i]]==undefined){
                    console.log("caseInfo",item[i],caseInfo[item[i]])
                    type=true
                }
            }
            
            if(type){
                Modal.alert('提示', "案件信息不完整", [
                    { text: 'OK', onPress: () => {}},
                ]);
                return
            }
          }

          //将同行执法人的和第一执法人的姓名和id转化未字符串  增加两个字段存放 
          //还原以前的数据结构不影响接口逻辑
          caseInfo.undertakerNameList=`${caseInfo.undertakerName},${caseInfo.undertaker2Name}`
          caseInfo.undertakerIdList=`${caseInfo.undertaker},${caseInfo.undertaker2}`
          caseInfo.undertaker2=caseInfo.undertakerIdList?caseInfo.undertakerIdList.split(",")[1]:''
          caseInfo.undertaker2Name=caseInfo.undertakerNameList?caseInfo.undertakerNameList.split(",")[1]:''
          caseInfo.undertakerNum2=caseInfo.undertakerNum2?caseInfo.undertakerNum2.split(",")[0]:''
          delete caseInfo.undertakerNum
          delete caseInfo.undertakerNum2
        }
       
        let submitData = {
            counterpartType: counterpartType,
            ...caseInfo,
            ...providerObj,
            caseLitigants: caseLitigants,
            ...documentInfo,
            casePendingMatters:[],
            acceptPendingMatters: [],
        }

        if(submitData.casePendingMatter && submitData.casePendingMatter.additionalOperations) {
            submitData.additionalOperations = submitData.casePendingMatter.additionalOperations
        }
        if(submitData.casePendingMatter && submitData.casePendingMatter.nextHandlerOfficerIds){
            submitData.casePendingMatter.officers = submitData.casePendingMatter.nextHandlerOfficerIds.map(
                item => {
                    return { officerId: parseInt(item) };
                }
            );
        }
        if(submitData.inspectionPendingMatter && submitData.inspectionPendingMatter.nextHandlerOfficerIds){
            submitData.inspectionPendingMatter.officers = submitData.inspectionPendingMatter.nextHandlerOfficerIds.map(
                item => {
                    return { officerId: parseInt(item) };
                }
            );
        }
        // inspectionActionRecord
        if(submitData.inspectionPendingMatter){
            submitData.inspectionPendingMatter.inspectionActionRecord = submitData.inspectionPendingMatter.caseActionRecord
        }

        if(this.type === 'inspection'){
            submitData.inspectionPendingMatter = {
                ...submitData.casePendingMatter,
                inspectionActionRecord : submitData.casePendingMatter.caseActionRecord
            }
        }
        //可填案件文书列表
        let documentInfoList=documentInfo.documentRequired?JSON.parse(documentInfo.documentRequired):[]
        for (let i=0,docList=documentInfoList.length;i<docList;i++){
            let k=0
            if(docList.isRequird===1){
                for (let j=0,caseL=caseTextData.length;j<caseL;j++){
                    if(caseL.type==docList.value){

                    }
                }
            }
        }

        let saveUrl = saveCaseReportUrl
        if(submitType === 'post'){
            // 新增
            if(documentInfo && documentInfo.casePendingMatter && documentInfo.casePendingMatter.linkHandleName){
                submitData.inspectionPendingMatter = null
                if(reportType === 'clue'){
                    saveUrl = saveAcceptCaseUrl
                    let acceptPendingMatter = {
                        ...submitData.casePendingMatter,
                        acceptActionRecord:submitData.casePendingMatter.caseActionRecord
                    }
                    submitData.acceptPendingMatters.push(acceptPendingMatter)
                }else {
                    submitData.casePendingMatters.push(submitData.casePendingMatter)
                }
            } else {
                saveUrl = saveCaseRecordsUrl
            }
        }else {
            if(!this.state.WayId){
                Modal.alert('提示', "请选择巡查上报方式", [
                    { text: 'OK', onPress: () => {}},
                ]);
                return
            }
            if(this.type === 'inspection'){ // 修改
                saveUrl = saveCaseRecordsUrl
                submitData.inspectionPendingMatter.id = this.matterId
            }else if(this.type === 'clue'){
                saveUrl = saveAcceptCaseUrl
                submitData.casePendingMatter.id = this.matterId
                let acceptPendingMatter = {
                    ...submitData.casePendingMatter,
                    acceptActionRecord: submitData.casePendingMatter.caseActionRecord
                }
                submitData.acceptPendingMatters.push(acceptPendingMatter)
            }else {
                saveUrl = saveCaseReportUrl
                submitData.casePendingMatter.id = this.matterId
                submitData.casePendingMatters.push(submitData.casePendingMatter)
            }
        }
        // 文书列表替换
        let items = [];
        let inspectionText = {};

        for (let j = 0, len = caseTextData.length; j < len; j++) {
            if(!caseTextData[j].caseCode){
                caseTextData[j].wsPath=''
            }
            const item = caseTextData[j];
            if (item.type === "XCWS") {
                // 巡查文书
                inspectionText = item;
            } else {
                items.push(item);
            }
        }
       

        submitData.caseTexts = items;
        submitData.inspectionText = inspectionText;

        console.log("submitData",submitData.casePendingMatter.caseActionRecord)
        // return;
        const key = ToastUtil.loading('保存中...')
        
     
        HttpUtils.request({
            url: saveUrl,
            type: submitType, // post  put
            data: submitData
        }).then(res=>{
            ToastUtil.remove(key)
            if(res && !res.status){
                ToastUtil.info('提交成功')
                NavigationUtil.goPage('IndexPage')
            }else if(res){
                ToastUtil.info(res.message)
                NavigationUtil.goPage('IndexPage')
            }else{
                ToastUtil.info(res.message)
            }
        }).catch((e)=>{
            console.log(e);
            ToastUtil.remove(key)
        })
        // const key = ToastUtil.loading('保存中...')
        // setTimeout(()=>{
        //     ToastUtil.remove(key)
        //     ToastUtil.info('保存成功')
        //     NavigationUtil.goPage('IndexPage')
        // }, 2000)
    }
    handleTabChange(obj, index) {
        if (this.state.index !== index) {
            this.state.tabIndex = index;
        }
    }

}
